# -*- coding: utf-8 -*-
# @Time    : 2020/10/18 15:47
# @Author  : liupengfei
# @File    : serializers.py


from rest_framework import serializers
from rest_framework_jwt.serializers import JSONWebTokenSerializer
from django.contrib.auth import get_user_model, authenticate
from rest_framework_jwt.settings import api_settings
from apps.member.models import Member
from utils.exceptions import CustomError

User = get_user_model()
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER


class UserJWTSerializer(JSONWebTokenSerializer):
    '''登录token获取'''

    def validate(self, attrs):
        credentials = {
            self.username_field: attrs.get(self.username_field),
            'password': attrs.get('password')
        }

        if all(credentials.values()):
            user = authenticate(**credentials)

            if user:
                payload = jwt_payload_handler(user)
                return {
                    'token': jwt_encode_handler(payload),
                    'user_id': user.id,
                    'username': user.username

                }
        msg = '账号密码错误！'
        raise CustomError(msg)


class UserJwtSerializer(serializers.ModelSerializer):
    '''中间件:刷新token返回的数据'''

    class Meta:
        model = User
        fields = ('username', 'nickname', 'is_staff')
